package linear.queue.base;

/**
 * 数组实现队列
 *
 * @author yeyangtao created at 10:15 2020/9/23
 */
public class MyArrayQueue<T> implements MyQueue<T> {
    Object[] value;
    int head = 0;
    int tail = 0;
    //数组大小
    int size = 16;

    public MyArrayQueue() {
        value = new Object[size];
    }

    public MyArrayQueue(int size) {
        value = new Object[size];
        this.size = size;
    }

    //扩容
//    @Override
//    public void offer(Object o) {
//        //队列满了
//        if (tail == capacity) {
//            head = 0;
//            tail = value.length - 1;
//            //扩容 迁移数据
//            capacity = capacity << 1;
//            value = Arrays.copyOf(value, capacity);
//        }
//        value[tail++] = o;
//    }
    @Override
    public boolean offer(Object o) {
        //队列满了
        if (head == 0 && tail == size) return false;
        //未满
        if (head != 0 && tail == size) {
            //数据搬运 System.arraycopy(value, head, value, 0, tail - head);
            for (int i = head; i < tail; i++) {
                value[i - head] = value[i];
            }
            tail = tail - head;
            head = 0;
        }
        value[tail++] = o;
        return true;
    }

    @Override
    public T poll() {
        if (head == tail) return null;
        @SuppressWarnings("unchecked")
        T result = (T) value[head++];
        return result;
    }

    @Override
    public T peek() {
        if (head == tail) return null;
        @SuppressWarnings("unchecked")
        T result = (T) value[head];
        return result;
    }

    @Override
    public boolean isEmpty() {
        return tail - head == 0;
    }

    @Override
    public int size() {
        return tail - head;
    }

    @Override
    public String toString() {
        if (value == null) return "null";
        if (tail - head == 0) return "[]";
        StringBuilder sb = new StringBuilder("[");
        for (int i = head; i < tail; i++) {
            sb.append(value[i].toString());
            if (i + 1 < tail) sb.append(", ");
        }
        sb.append("]");
        return sb.toString();
    }
}
